package com.lightspring.core.io;

import cn.hutool.core.lang.Assert;
import com.lightspring.utils.ClassUtils;

import java.net.MalformedURLException;
import java.net.URL;

public class DefaultResourceLoader implements ResourceLoader{


    private ClassLoader classLoader;

    public DefaultResourceLoader(ClassLoader classLoader) {
        this.classLoader = classLoader;
    }

    public Resource getResource(String location) {

        Assert.notNull(location, "Location must not be null");

        // 此处可扩展设计不同的资源加载器进行处理

        // 如果以 classpath 开头 则 创建ClassPathResource
         if (location.startsWith(CLASSPATH_URL_PREFIX)) {
            return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());
        } else {
            try {
                // Try to parse the location as a URL...
                URL url = new URL(location);
                // 网络信息出加载资源内容
                return new UrlResource(url);

            } catch (MalformedURLException ex) {
                // 利用检查异常来进行处理
                // 所谓检查异常就是在使用方法时必须对异常进行检查，这属于jdk默认规范
                return new FileSystemResource(location);
            }
        }
    }

    @Override
    public ClassLoader getClassLoader() {
        return (this.classLoader != null ? this.classLoader : ClassUtils.getDefaultClassLoader());
    }


}
